import sys

from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
from qfluentwidgets import InfoBar, InfoBarPosition

from HttpApi.DataManager import DataManager
from HttpApi.JsonHttpClient import JsonHttpClient
from user_page import Ui_Form
# 1. 创建一个自定义的窗口类，继承自 QWidget
class UserPage(QWidget, Ui_Form):
    def __init__(self):
        super().__init__()  # 调用父类的 __init__ 方法
        self.manager = DataManager()
        self.setupUi(self)  # 调用 UI 类的 setupUi 方法，设置窗口的 UI
        # 更新头像图片
        self.listWidget_2.setImage(':/images/img/头像.png')
        self.listWidget_2.setRadius(40)
        # 提示登录成功
        self.show_success_login()
        self.httpClient = JsonHttpClient()


        self.exitLogin.clicked.connect(self.handle_logout)
        self.updata_vip.clicked.connect(self.handle_up_vip)
        self.updata_user.clicked.connect(self.handle_up_user)
        self.sendPoints.clicked.connect(self.handle_up_points)

        # 设置展示框为只读
        self.name.setReadOnly(True)
        self.userid.setReadOnly(True)
        self.account.setReadOnly(True)
        self.points_s.setReadOnly(True)
        self.level.setReadOnly(True)


    def handle_up_points(self):
        # 读取points
        points = self.points.text()
        # 发送get: /user-status/update/points/{points} , 并携带请求头
        get = self.httpClient.get(f'/user-status/update/points/{points}', headers={'Authorization': self.manager.get_cached_data('token')})
        if get['code'] != 200:
            print("修改积分失败")
            self.show_error_info(get['msg'])
            return
        self.show_success_info("修改积分成功")
        print("积分：", points)
        print("修改积分按钮被点击了")

    def handle_up_user(self):
        # 修改name/userid/account/points_s/level
        userinfo = self.manager.get_cached_data('userinfo')
        token = self.manager.get_cached_data('token')
        if userinfo is None or token is None:
            print("请先登录")
            return
        # 发送请求get: /user-status/info, 并携带请求头
        get = self.httpClient.get('/user-status/info', headers={'Authorization': token})
        if get['code'] != 200:
            print("获取用户信息失败")
            self.show_error_info(get['msg'])
            return
        self.show_success_info("获取用户信息成功")
        name = userinfo['name']
        userid = userinfo['userId']
        account = userinfo['account']
        points_s = get['data']['points']
        level = get['data']['name']
        # 更新UI
        self.name.setText(str(name))
        self.userid.setText(str(userid))
        self.account.setText(str(account))
        self.points_s.setText(str(points_s))
        self.level.setText(str(level))

    def handle_up_vip(self):
        # 发送请求 get: /user-status/update/level, 并携带请求头
        get = self.httpClient.get('/user-status/update/level', headers={'Authorization': self.manager.get_cached_data('token')})
        if get['code'] != 200:
            print("申请会员提交失败")
            self.show_error_info(get['msg'])
            return
        self.show_success_info("申请会员已提交")
        print("升级会员按钮被点击了")

    def handle_logout(self):
        # 清空数据
        self.manager.clear_cache()
        print("退出登录按钮被点击了")

    def show_success_login(self):
        """显示成功信息"""
        InfoBar.success(
            title='登录成功',
            content="千寻云欢迎您!",
            orient=InfoBarPosition.TOP_LEFT,
            isClosable=True,
            duration=3000,
            parent=self
        )
    def show_success_info(self,msg):
        """显示成功信息"""
        InfoBar.success(
            title='成功',
            content=msg,
            orient=InfoBarPosition.TOP_LEFT,
            isClosable=True,
            duration=3000,
            parent=self
        )

    def show_error_info(self, msg):
        """显示错误信息"""
        InfoBar.error(
            title='登录失败',
            content=msg,
            orient=InfoBarPosition.TOP_LEFT,
            isClosable=True,
            duration=3000,
            parent=self
        )


# --- 程序的入口部分 ---
if __name__ == '__main__':
    # 设置应用程序高DPI缩放支持
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
    # 2. 创建应用程序实例
    app = QApplication(sys.argv)
    # 3. 创建我们自定义的窗口实例
    my_app_window = UserPage()

    # 4. 显示窗口
    my_app_window.show()

    # 5. 启动事件循环
    sys.exit(app.exec())
